package com.xmtlxx.oms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.xmtlxx.oms.domain.Box;
import com.xmtlxx.oms.domain.BoxDept;
import com.xmtlxx.oms.domain.bo.BoxBo;
import com.xmtlxx.oms.domain.vo.BoxVo;
import com.xmtlxx.oms.mapper.BoxDeptMapper;
import com.xmtlxx.oms.mapper.BoxMapper;
import com.xmtlxx.oms.service.IBoxService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 箱子Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-12-07
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class BoxServiceImpl implements IBoxService {

    private final BoxMapper baseMapper;

    private final BoxDeptMapper boxDeptMapper;

    /**
     * 查询箱子
     *
     * @param id 箱子主键
     * @return 箱子
     */
    @Override
    public BoxVo queryById(String id){
        //return baseMapper.selectVoById(id);
        return baseMapper.selectBoxVoByID(id);
    }

    /**
     * 查询箱子列表
     *
     * @param bo 箱子
     * @return 箱子
     */
    @Override
    public TableDataInfo<BoxVo> queryPageList(BoxBo bo, PageQuery pageQuery) {
       // LambdaQueryWrapper<Box> lqw = buildQueryWrapper(bo);
       // Page<BoxVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<BoxVo> result = baseMapper.selectPageBoxList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询箱子列表
     *
     * @param bo 箱子
     * @return 箱子
     */
    @Override
    public List<BoxVo> queryList(BoxBo bo) {
       // LambdaQueryWrapper<Box> lqw = buildQueryWrapper(bo);
       // return baseMapper.selectVoList(lqw);
        return baseMapper.selectBoxList(bo);
    }

    private LambdaQueryWrapper<Box> buildQueryWrapper(BoxBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Box> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getBoxNo()), Box::getBoxNo, bo.getBoxNo());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), Box::getType, bo.getType());
        lqw.eq(bo.getDeptId() != null, Box::getDeptId, bo.getDeptId());
        lqw.eq(bo.getCreateDept() != null, Box::getCreateDept, bo.getCreateDept());
        lqw.eq(StringUtils.isNotBlank(bo.getModel()), Box::getModel, bo.getModel());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Box::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), Box::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增箱子
     *
     * @param bo 箱子
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(BoxBo bo) {
        boolean flag = false;
        Box add = BeanUtil.toBean(bo, Box.class);
        validEntityBeforeSave(add);

        List<Box> boxList = new ArrayList<>();
        if(bo.getStartNo() != null && bo.getEndNo() != null){
            Integer forIndex = bo.getEndNo() - bo.getStartNo();
            for (int i = 0;i<= forIndex;i++){
                //填充UUID
                add.setId(IdUtil.simpleUUID());
                add.setStatus("0");
                add.setDelFlag("0");
//                add.setBoxNo();

                add.setName(getBoxName(bo.getName(),i+1));
                add.setSeq(bo.getStartNo()+i);
                add.setCreateDept(LoginHelper.getDeptId());
                boxList.add(add);
                flag = baseMapper.insert(add) > 0;

                //领用记录
                BoxDept boxDept = new BoxDept();
                boxDept.setId(IdUtil.simpleUUID());
                boxDept.setBoxId(add.getId());
                boxDept.setBoxDept(add.getDeptId());
                boxDept.setDelFlag("0");
                boxDept.setBoxNo(add.getBoxNo());
                boxDept.setStatus("0");
                boxDeptMapper.insert(boxDept);
            }
        }
        return flag;
    }

    /**
     * 修改箱子
     *
     * @param bo 箱子
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(BoxBo bo) {
        Box update = BeanUtil.toBean(bo, Box.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public BoxVo updateScanByBo(BoxBo bo) {
        BoxVo vo = new BoxVo();
        Box box = baseMapper.selectOne(new LambdaQueryWrapper<Box>().eq(Box::getBoxNo,bo.getBoxNo()).eq(Box::getDeptId,LoginHelper.getDeptId()));
        if(box == null){
            box = new Box();
            box.setId(IdUtil.simpleUUID());
            box.setBoxNo(bo.getBoxNo());
            box.setDelFlag("0");
            box.setCreateDept(LoginHelper.getDeptId());
            box.setStatus("0");
            box.setDeptId(LoginHelper.getDeptId());
            baseMapper.insert(box);
        }


        //使用记录添加

//        BoxDeptBo boxDeptBo = new BoxDeptBo();
//        boxDeptBo.setBoxDept(LoginHelper.getDeptId());
//        boxDeptBo.setBoxNo(box.getBoxNo());
//        List<BoxDeptVo> boxDeptVos = boxDeptMapper.selectBoxDeptList(boxDeptBo);

//        boolean flag = true;
        //判断当前扫描账号是否有待使用记录，没有则添加一条待使用记录
//        if(boxDeptVos != null && boxDeptVos.size() > 0){
//              for (BoxDeptVo enty:boxDeptVos){
//                  if(enty.getStatus().equals("0")){
//                      flag = false;
//                      continue;
//                  }
//              }
//        }
//        if(flag){
//            BoxDept boxDept = new BoxDept();
//            boxDept.setId(IdUtil.simpleUUID());
//            boxDept.setBoxId(box.getId());
//            boxDept.setBoxNo(box.getBoxNo());
//            boxDept.setBoxDept(box.getDeptId());
//            boxDept.setStatus("0");
//            boxDept.setDelFlag("0");
//            boxDeptMapper.insert(boxDept);
//        }


        BeanUtil.copyProperties(box,vo);
        return vo;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Box entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除箱子
     *
     * @param ids 需要删除的箱子主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    private String getBoxNo(Integer nums,Integer size){
        return  StringUtils.padl(nums,size);
    }

    private String getBoxName(String name,Integer nums){
        String boxName = "";
        if(nums.toString().length() == 1){
            boxName = name+"0"+nums;
        }else {
            boxName = name+nums.toString();
        }
        return boxName;
    }
}
